<template>
  <div class="business-view">
    <!-- 面包屑导航 -->
    <div class="bread-crumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>首页</el-breadcrumb-item>
        <el-breadcrumb-item>商机管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 搜索条件区域 -->
    <div class="search-container">
      <el-form :inline="true" size="small" :model="searchParams">
        <el-form-item label="商机ID:">
          <el-input
            v-model="searchParams.businessId"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="客户姓名:">
          <el-input v-model="searchParams.name" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="手机号:">
          <el-input
            v-model="searchParams.phone"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="商机状态:">
          <el-select v-model="searchParams.status" placeholder="请选择">
            <el-option
              v-for="item in businessStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="归属人:">
          <el-input
            v-model="searchParams.assignName"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-container">
      <el-button type="primary" size="small" @click="openAddBusinessDialog"
        >+ 新建商机</el-button
      >
    </div>

    <!-- 表格和分页容器 -->
    <div class="content-wrapper">
      <!-- 表格内容容器 -->
      <div class="table-wrapper">
        <el-table
          :data="businessStore.businesses"
          v-loading="businessStore.loading"
          stripe
          height="500"
          style="width: 100%"
        >
          <el-table-column
            prop="id"
            label="商机ID"
            width="80"
          ></el-table-column>
          <el-table-column
            prop="name"
            label="姓名"
            width="100"
          ></el-table-column>
          <el-table-column prop="phone" label="手机号" width="120">
            <template #default="scope">
              {{ formatPhone(scope.row.phone) }}
            </template>
          </el-table-column>
          <el-table-column prop="subject" label="意向学科" width="180">
            <template #default="scope">
              {{ formatSubject(scope.row.subject) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="assignName"
            label="归属人"
            width="100"
          ></el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            width="150"
          ></el-table-column>
          <el-table-column prop="status" label="商机状态" width="100">
            <template #default="scope">
              <span :class="getStatusClass(scope.row.status)">{{
                formatBusinessStatus(scope.row.status)
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="nextTime"
            label="下次跟进时间"
            width="150"
          ></el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <!-- 分配按钮：只有管理员可以分配，且只在待分配状态显示 -->
              <template
                v-if="scope.row.status === 1 && authStore.roleLabel === 'admin'"
              >
                <el-button
                  type="text"
                  size="small"
                  @click="openAssignDialog(scope.row)"
                  >分配</el-button
                >
              </template>

              <!-- 跟进按钮：只有商机专员可以跟进，且只在待跟进和跟进中状态显示，并且是归属人 -->
              <template
                v-if="
                  (scope.row.status === 2 || scope.row.status === 3) &&
                  scope.row.userId === authStore.userId
                "
              >
                <el-button
                  type="text"
                  size="small"
                  @click="openFollowDialog(scope.row)"
                  >跟进</el-button
                >
              </template>

              <!-- 踢回公海按钮：只有商机专员可以踢回公海，且只在待跟进和跟进中状态显示，并且是归属人 -->
              <template
                v-if="
                  (scope.row.status === 2 || scope.row.status === 3) &&
                  scope.row.userId === authStore.userId
                "
              >
                <el-button
                  type="text"
                  size="small"
                  @click="openRecycleConfirm(scope.row)"
                  >踢回公海</el-button
                >
              </template>

              <!-- 转客户按钮：只有商机专员可以转客户，且只在待跟进和跟进中状态显示，并且是归属人 -->
              <template
                v-if="
                  (scope.row.status === 2 || scope.row.status === 3) &&
                  scope.row.userId === authStore.userId
                "
              >
                <el-button
                  type="text"
                  size="small"
                  @click="openToCustomerConfirm(scope.row)"
                  >转客户</el-button
                >
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页容器 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="businessStore.pagination.page"
          v-model:page-size="businessStore.pagination.pageSize"
          layout="total, prev, pager, next, sizes, jumper"
          :total="businessStore.pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 添加商机模态框 -->
    <el-dialog
      v-model="dialogVisible.addBusiness"
      title="添加商机"
      width="600px"
      center
    >
      <el-form
        label-width="80px"
        size="small"
        :model="addBusinessForm"
        :rules="addBusinessRules"
        ref="addBusinessRef"
      >
        <div class="form-row">
          <el-form-item
            label="* 客户姓名:"
            prop="name"
            required
            class="form-item"
          >
            <el-input
              v-model="addBusinessForm.name"
              placeholder="请输入客户姓名"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="* 手机号:"
            prop="phone"
            required
            class="form-item"
          >
            <el-input
              v-model="addBusinessForm.phone"
              placeholder="请输入手机号"
              maxlength="11"
            ></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="性别:" prop="gender" class="form-item">
            <el-select v-model="addBusinessForm.gender" placeholder="请选择">
              <el-option
                v-for="item in genderOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="年龄:" prop="age" class="form-item">
            <el-input
              v-model.number="addBusinessForm.age"
              type="number"
              placeholder="请输入年龄"
              min="0"
              max="150"
            ></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="微信号:" prop="wechat" class="form-item">
            <el-input
              v-model="addBusinessForm.wechat"
              placeholder="请输入微信号"
            ></el-input>
          </el-form-item>
          <el-form-item label="QQ:" prop="qq" class="form-item">
            <el-input
              v-model="addBusinessForm.qq"
              placeholder="请输入QQ"
            ></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item
            label="* 意向学科:"
            prop="subject"
            required
            class="form-item"
          >
            <el-select
              v-model="addBusinessForm.subject"
              placeholder="请选择"
              @change="handleSubjectChange"
              :disabled="!addBusinessForm.channel"
            >
              <el-option
                v-for="item in dynamicSubjectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="意向课程:" prop="courseId" class="form-item">
            <el-select
              v-model="addBusinessForm.courseId"
              placeholder="请选择"
              :disabled="!addBusinessForm.subject"
            >
              <el-option
                v-for="item in dynamicCourseOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="学历:" prop="degree" class="form-item">
            <el-select v-model="addBusinessForm.degree" placeholder="请选择">
              <el-option
                v-for="item in degreeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="在职情况:" prop="jobStatus" class="form-item">
            <el-select v-model="addBusinessForm.jobStatus" placeholder="请选择">
              <el-option
                v-for="item in jobStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item
            label="* 渠道来源:"
            prop="channel"
            required
            class="form-item"
          >
            <el-select
              v-model="addBusinessForm.channel"
              placeholder="请选择"
              @change="handleChannelChange"
            >
              <el-option
                v-for="item in channelOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注:" prop="remark" class="form-item">
            <el-input
              v-model="addBusinessForm.remark"
              placeholder="备注信息，最多50字"
              maxlength="50"
            ></el-input>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <el-button @click="cancelAddBusiness">取消</el-button>
        <el-button type="primary" @click="confirmAddBusiness">确定</el-button>
      </template>
    </el-dialog>

    <!-- 分配商机模态框 -->
    <el-dialog
      v-model="dialogVisible.assignBusiness"
      title="分配商机"
      width="400px"
      center
    >
      <el-form
        label-width="80px"
        size="small"
        :model="assignForm"
        :rules="assignRules"
        ref="assignRef"
      >
        <el-form-item label="* 请选择人员:" prop="userId" required>
          <el-select
            v-model="assignForm.userId"
            placeholder="请选择"
            :loading="loadingBusinessStaff"
          >
            <el-option
              v-for="item in businessStaffOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelAssign">取消</el-button>
        <el-button type="primary" @click="confirmAssign">确定</el-button>
      </template>
    </el-dialog>

    <!-- 确认对话框 - 踢回公海 -->
    <el-dialog
      v-model="dialogVisible.confirmRecycle"
      title="确认"
      width="300px"
      center
    >
      <div class="confirm-text">确定将该商机踢回公海吗?</div>
      <template #footer>
        <el-button @click="cancelRecycle">取消</el-button>
        <el-button type="primary" @click="confirmRecycle">确定</el-button>
      </template>
    </el-dialog>

    <!-- 确认对话框 - 转客户 -->
    <el-dialog
      v-model="dialogVisible.confirmToCustomer"
      title="确认"
      width="300px"
      center
    >
      <div class="confirm-text">确定将该商机转为客户吗?</div>
      <template #footer>
        <el-button @click="cancelToCustomer">取消</el-button>
        <el-button type="primary" @click="confirmToCustomer">确定</el-button>
      </template>
    </el-dialog>

    <!-- 跟进商机模态框 -->
    <el-dialog
      v-model="dialogVisible.followBusiness"
      :title="`跟进商机(线索ID:${currentBusiness?.id || '-'})`"
      width="700px"
      center
    >
      <!-- 客户基本信息 -->
      <el-form
        label-width="80px"
        size="small"
        :model="businessDetail"
        style="margin-bottom: 20px"
      >
        <div class="form-row">
          <el-form-item label="* 手机号:" class="form-item">
            <el-input
              v-model="followForm.phone"
              placeholder="请输入手机号"
              maxlength="11"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="* 客户姓名:" class="form-item">
            <el-input
              v-model="followForm.name"
              placeholder="请输入客户姓名"
            ></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="性别:" class="form-item">
            <el-select
              v-model="followForm.gender"
              placeholder="请选择"
            >
              <el-option
                v-for="(item, index) in genderOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="年龄:" class="form-item">
            <el-input
              v-model.number="followForm.age"
              type="number"
              placeholder="请输入年龄"
              min="0"
              max="150"
            ></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="微信号:" class="form-item">
            <el-input
              v-model="followForm.wechat"
              placeholder="请输入微信号"
            ></el-input>
          </el-form-item>
          <el-form-item label="QQ:" class="form-item">
            <el-input
              v-model="followForm.qq"
              placeholder="请输入QQ"
            ></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="意向学科:" class="form-item">
            <el-select
              v-model="followForm.subject"
              placeholder="请选择"
              @change="handleSubjectChangeFollow"
            >
              <el-option
                v-for="(item, index) in subjectOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="意向课程:" class="form-item">
            <el-select
              v-model="followForm.courseId"
              placeholder="请选择"
            >
              <el-option
                v-for="(item, index) in dynamicCourseOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="学历:" class="form-item">
            <el-select
              v-model="followForm.degree"
              placeholder="请选择"
            >
              <el-option
                v-for="(item, index) in degreeOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="在职状态:" class="form-item">
            <el-select
              v-model="followForm.jobStatus"
              placeholder="请选择"
            >
              <el-option
                v-for="(item, index) in jobStatusOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="渠道来源:" class="form-item">
            <el-select
              v-model="followForm.channel"
              placeholder="请选择"
              @change="handleChannelChangeFollow"
            >
              <el-option
                v-for="(item, index) in channelOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注:" class="form-item">
            <el-input
              v-model="followForm.remark"
              placeholder="备注信息"
            ></el-input>
          </el-form-item>
        </div>
      </el-form>

      <!-- 跟进信息表单 -->
      <el-form
        label-width="80px"
        size="small"
        :model="followForm"
        :rules="followRules"
        ref="followRef"
      >
        <div class="form-row">
          <el-form-item
            label="* 跟进状态:"
            prop="trackStatus"
            required
            class="form-item"
          >
            <el-select v-model="followForm.trackStatus" placeholder="请选择">
              <el-option
                v-for="(item, index) in trackStatusOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="* 沟通重点:"
            prop="keyItems"
            required
            class="form-item"
          >
            <el-select
              v-model="followForm.keyItems"
              placeholder="请选择"
              multiple
            >
              <el-option label="课程" value="课程"></el-option>
              <el-option label="价格" value="价格"></el-option>
              <el-option label="位置" value="位置"></el-option>
              <el-option label="时间" value="时间"></el-option>
              <el-option label="师资" value="师资"></el-option>
              <el-option label="项目" value="项目"></el-option>
              <el-option label="薪资" value="薪资"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item
            label="* 下次跟进:"            
            prop="nextTime"
            required
            class="form-item"
          >
            <el-date-picker
              v-model="followForm.nextTime"
              type="datetime"
              placeholder="选择日期时间"
              style="width: 200px"
              value-format="YYYY-MM-DD HH:mm:ss"
              :disabled-date="(time) => time.getTime() < Date.now() - 8.64e7"
              format="YYYY-MM-DD HH:mm"
              clearable
            >
              <template #prefix>
                <el-icon><Calendar /></el-icon>
              </template>
            </el-date-picker>
          </el-form-item>
          <el-form-item
            label="* 沟通纪要:"
            prop="record"
            required
            class="form-item"
          >
            <el-input
              v-model="followForm.record"
              type="textarea"
              placeholder="请输入沟通纪要"
              maxlength="150"
              show-word-limit
            ></el-input>
          </el-form-item>
        </div>
      </el-form>

      <!-- 历史沟通记录 -->
      <div class="history-section">
        <h3 style="margin-bottom: 15px; font-size: 14px; font-weight: 500">
          历史沟通记录
        </h3>
        <div v-if="trackRecords && trackRecords.length > 0">
          <el-table :data="trackRecords" size="small">
            <el-table-column
              prop="followTime"
              label="跟进时间"
              width="150"
            ></el-table-column>
            <el-table-column prop="keyItems" label="沟通重点" width="150">
              <template #default="scope">
                {{
                  scope.row && scope.row.keyItems
                    ? scope.row.keyItems.join(",")
                    : "-"
                }}
              </template>
            </el-table-column>
            <el-table-column prop="trackStatus" label="沟通状态" width="100">
              <template #default="scope">
                {{ scope.row ? formatTrackStatus(scope.row.trackStatus) : "-" }}
              </template>
            </el-table-column>
            <el-table-column
              prop="nextTime"
              label="下次跟进时间"
              width="150"
            ></el-table-column>
            <el-table-column
              prop="record"
              label="沟通纪要"
              width="200"
            ></el-table-column>
            <el-table-column
              prop="userName"
              label="跟进人"
              width="80"
            ></el-table-column>
          </el-table>
        </div>
        <div v-else style="text-align: center; color: #909399; padding: 20px">
          暂无历史沟通记录
        </div>
      </div>

      <template #footer>
        <el-button @click="cancelFollow">取消</el-button>
        <el-button type="primary" @click="confirmFollow">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Calendar } from "@element-plus/icons-vue";
import { useBusinessStore } from "@/stores/business";
import { useAuthStore } from "@/stores/auth";
import { useUserStore } from "@/stores/user";
import {
  createBusiness,
  assignBusiness,
  backToPool,
  toCustomer,
  followBusiness,
  getBusinessById,
} from "@/api/business";
import { getUsersByRole } from "@/api/user";
import {
  businessStatusMap,
  businessStatusOptions,
  subjectMap,
  subjectOptions,
  genderOptions,
  degreeOptions,
  jobStatusOptions,
  channelOptions,
  trackStatusMap,
  trackStatusOptions,
  regexRules,
  getSubjectsByChannel,
  formatPhone,
  formatSubject,
  formatBusinessStatus,
} from "@/utils/sysUtils";
import { useCourseStore } from "@/stores/course";

// 初始化store
const businessStore = useBusinessStore();
const authStore = useAuthStore();
const courseStore = useCourseStore();
const userStore = useUserStore();

// 表单引用
const addBusinessRef = ref(null);
const assignRef = ref(null);
const followRef = ref(null);

// 对话框可见状态
const dialogVisible = ref({
  addBusiness: false,
  assignBusiness: false,
  confirmRecycle: false,
  confirmToCustomer: false,
  followBusiness: false,
});

// 当前操作的商机
const currentBusiness = ref(null);

// 商机专员用户列表
const businessStaffOptions = ref([]);
// 加载商机专员的状态
const loadingBusinessStaff = ref(false);

// 搜索条件
const searchParams = ref({
  businessId: "",
  name: "",
  phone: "",
  status: "",
  assignName: "",
  subject: "",
  createTimeRange: [],
  nextFollowTimeRange: [],
});

// 添加商机表单数据
const addBusinessForm = ref({
  name: "",
  phone: "",
  gender: null,
  age: null,
  wechat: "",
  qq: "",
  subject: null,
  courseId: null,
  degree: null,
  jobStatus: null,
  channel: null,
  remark: "",
});

// 动态意向学科选项（根据渠道来源变化）
const dynamicSubjectOptions = ref([]);

// 动态课程选项（根据意向学科变化）
const dynamicCourseOptions = ref([]);

// 添加商机表单验证规则
const addBusinessRules = {
  name: [
    { required: true, message: "请输入客户姓名", trigger: "blur" },
    {
      pattern: regexRules.name,
      message: "姓名长度应在1-20个字符之间",
      trigger: "blur",
    },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: regexRules.phone,
      message: "请输入正确的手机号格式",
      trigger: "blur",
    },
  ],
  wechat: [
    {
      pattern: regexRules.wechat,
      message: "请输入正确的微信号格式",
      trigger: "blur",
    },
  ],
  qq: [
    {
      pattern: regexRules.qq,
      message: "请输入正确的QQ号格式",
      trigger: "blur",
    },
  ],
  subject: [{ required: true, message: "请选择意向学科", trigger: "change" }],
  channel: [{ required: true, message: "请选择渠道来源", trigger: "change" }],
};

// 处理渠道来源变化，更新可用的意向学科选项
const handleChannelChange = () => {
  if (addBusinessForm.value.channel) {
    // 根据选择的渠道来源获取关联的意向学科
    dynamicSubjectOptions.value = getSubjectsByChannel(
      addBusinessForm.value.channel
    );
    // 重置意向学科和课程选择
    addBusinessForm.value.subject = null;
    addBusinessForm.value.courseId = null;
    dynamicCourseOptions.value = [];
  } else {
    dynamicSubjectOptions.value = [];
    addBusinessForm.value.subject = null;
    addBusinessForm.value.courseId = null;
    dynamicCourseOptions.value = [];
  }
};

// 处理意向学科变化，更新可用的课程选项
const handleSubjectChange = () => {
  if (addBusinessForm.value.subject) {
    // 从课程store获取对应学科的课程
    const courses = courseStore.getCoursesBySubject(
      addBusinessForm.value.subject
    );
    dynamicCourseOptions.value = courses.map((course) => ({
      label: course.name,
      value: course.id,
    }));
    // 重置课程选择
    addBusinessForm.value.courseId = null;
  } else {
    dynamicCourseOptions.value = [];
    addBusinessForm.value.courseId = null;
  }
};

// 跟进模态框中处理意向学科变化
const handleSubjectChangeFollow = () => {
  if (followForm.value.subject) {
    // 从课程store获取对应学科的课程
    const courses = courseStore.getCoursesBySubject(
      followForm.value.subject
    );
    dynamicCourseOptions.value = courses.map((course) => ({
      label: course.name,
      value: course.id,
    }));
    // 重置课程选择
    followForm.value.courseId = null;
  } else {
    dynamicCourseOptions.value = [];
    followForm.value.courseId = null;
  }
};

// 跟进模态框中处理渠道变化
const handleChannelChangeFollow = () => {
  if (followForm.value.channel) {
    // 根据渠道来源更新可用的意向学科选项
    dynamicSubjectOptions.value = getSubjectsByChannel(followForm.value.channel);
    // 重置学科和课程选择
    followForm.value.subject = null;
    followForm.value.courseId = null;
    dynamicCourseOptions.value = [];
  } else {
    dynamicSubjectOptions.value = [];
    followForm.value.subject = null;
    followForm.value.courseId = null;
    dynamicCourseOptions.value = [];
  }
};

// 分配商机表单数据
const assignForm = ref({
  userId: null,
});

// 分配表单验证规则
const assignRules = {
  userId: [{ required: true, message: "请选择分配人员", trigger: "change" }],
};

// 商机详情数据
const businessDetail = reactive({});
// 历史沟通记录
const trackRecords = ref([]);

// 跟进商机表单数据 - 初始化为完整对象，避免null访问
const followForm = ref({
  id: null,
  phone: "",
  name: "",
  gender: null,
  age: null,
  wechat: "",
  qq: null,
  subject: null,
  courseId: null,
  degree: null,
  jobStatus: null,
  channel: null,
  remark: "",
  trackStatus: null,
  keyItems: [],
  nextTime: "",
  record: "",
});

// 跟进表单验证规则
const followRules = {
  trackStatus: [
    { required: true, message: "请选择跟进状态", trigger: "change" },
  ],
  keyItems: [{ required: true, message: "请选择沟通重点", trigger: "change" }],
  nextTime: [
    { required: true, message: "请选择下次跟进时间", trigger: "change" },
  ],
  record: [
    { required: true, message: "请输入沟通纪要", trigger: "blur" },
    {
      min: 1,
      max: 150,
      message: "沟通纪要长度应在1-150个字符之间",
      trigger: "blur",
    },
  ],
};

// 根据状态获取样式类
const getStatusClass = (status) => {
  const statusClassMap = {
    1: "status-pending",
    2: "status-waiting",
    3: "status-following",
    4: "status-recycled",
    5: "status-converted",
  };
  return statusClassMap[status] || "status-default";
};

// 处理分页大小变化
const handleSizeChange = async (size) => {
  businessStore.setPagination(businessStore.pagination.page, size);
  await loadBusinesses();
};

// 处理当前页码变化
const handleCurrentChange = async (current) => {
  businessStore.setPagination(current, businessStore.pagination.pageSize);
  await loadBusinesses();
};

// 加载商机列表
const loadBusinesses = async () => {
  try {
    await businessStore.fetchBusinesses(searchParams.value);
  } catch (error) {
    ElMessage.error("加载商机列表失败");
  }
};

// 重置搜索条件
const resetSearch = async () => {
  searchParams.value = {
    businessId: "",
    name: "",
    phone: "",
    status: "",
    assignName: "",
  };
  // 重置页码到第一页
  businessStore.setPagination(1, businessStore.pagination.pageSize);
  // 重新加载数据
  await loadBusinesses();
};

// 搜索
const search = async () => {
  businessStore.setPagination(1, businessStore.pagination.pageSize);
  await loadBusinesses();
};

// 打开添加商机对话框
const openAddBusinessDialog = () => {
  // 重置表单数据
  addBusinessForm.value = {
    name: "",
    phone: "",
    gender: null,
    age: null,
    wechat: "",
    qq: "",
    subject: null,
    courseId: null,
    degree: null,
    jobStatus: null,
    channel: null,
    remark: "",
  };
  // 重置动态选项
  dynamicSubjectOptions.value = [];
  dynamicCourseOptions.value = [];

  if (addBusinessRef.value) {
    addBusinessRef.value.resetFields();
  }
  dialogVisible.value.addBusiness = true;
};

// 取消添加商机
const cancelAddBusiness = () => {
  dialogVisible.value.addBusiness = false;
};

// 确认添加商机
const confirmAddBusiness = async () => {
  if (!addBusinessRef.value) return;

  try {
    await addBusinessRef.value.validate();

    const response = await createBusiness(addBusinessForm.value);
    if (response.code === 1) {
      ElMessage.success("添加商机成功");
      dialogVisible.value.addBusiness = false;
      await loadBusinesses();
    } else {
      ElMessage.error(response.message || "添加失败");
    }
  } catch (error) {
    if (error.name !== "Error") {
      return; // 表单验证失败
    }
    ElMessage.error("添加商机失败");
  }
};

// 打开分配对话框
const openAssignDialog = async (business) => {
  currentBusiness.value = business;
  assignForm.value.userId = null;
  if (assignRef.value) {
    assignRef.value.resetFields();
  }

  // 加载商机专员用户列表
  await loadBusinessStaff();

  dialogVisible.value.assignBusiness = true;
};

// 加载商机专员用户列表
const loadBusinessStaff = async () => {
  loadingBusinessStaff.value = true;
  try {
    // 使用正确的角色标识: business_operator
    const response = await getUsersByRole("business_operator");
    if (response.code === 1) {
      businessStaffOptions.value = response.data.map((user) => ({
        label: user.name,
        value: user.id,
      }));

      // 如果没有数据，添加mock数据以便展示
      if (businessStaffOptions.value.length === 0) {
        // 根据数据库表中的示例数据创建商机专员mock数据
        businessStaffOptions.value = [
          { label: "李四", value: 2 },
          { label: "王五", value: 3 },
          { label: "赵六", value: 4 },
        ];
      }
    } else {
      // 使用mock数据
      businessStaffOptions.value = [
        { label: "李四", value: 2 },
        { label: "王五", value: 3 },
        { label: "赵六", value: 4 },
      ];
    }
  } catch (error) {
    // API调用失败时使用mock数据
    businessStaffOptions.value = [
      { label: "李四", value: 2 },
      { label: "王五", value: 3 },
      { label: "赵六", value: 4 },
    ];
  } finally {
    loadingBusinessStaff.value = false;
  }
};

// 取消分配
const cancelAssign = () => {
  dialogVisible.value.assignBusiness = false;
};

// 确认分配
const confirmAssign = async () => {
  if (!assignRef.value || !currentBusiness.value) return;

  try {
    await assignRef.value.validate();

    const response = await assignBusiness(
      currentBusiness.value.id,
      assignForm.value.userId
    );
    if (response.code === 1) {
      ElMessage.success("分配成功");
      dialogVisible.value.assignBusiness = false;
      await loadBusinesses();
    } else {
      ElMessage.error(response.message || "分配失败");
    }
  } catch (error) {
    if (error.name !== "Error") {
      return; // 表单验证失败
    }
    ElMessage.error("分配失败");
  }
};

// 打开踢回公海确认
const openRecycleConfirm = (business) => {
  currentBusiness.value = business;
  dialogVisible.value.confirmRecycle = true;
};

// 取消踢回公海
const cancelRecycle = () => {
  dialogVisible.value.confirmRecycle = false;
};

// 确认踢回公海
const confirmRecycle = async () => {
  if (!currentBusiness.value) return;

  try {
    const response = await backToPool(currentBusiness.value.id);
    if (response.code === 1) {
      ElMessage.success("已成功踢回公海");
      dialogVisible.value.confirmRecycle = false;
      await loadBusinesses();
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    ElMessage.error("操作失败");
  }
};

// 打开转客户确认
const openToCustomerConfirm = (business) => {
  currentBusiness.value = business;
  dialogVisible.value.confirmToCustomer = true;
};

// 取消转客户
const cancelToCustomer = () => {
  dialogVisible.value.confirmToCustomer = false;
};

// 确认转客户
const confirmToCustomer = async () => {
  if (!currentBusiness.value) return;

  try {
    const response = await toCustomer(currentBusiness.value.id);
    if (response.code === 1) {
      ElMessage.success("已成功转为客户");
      dialogVisible.value.confirmToCustomer = false;
      await loadBusinesses();
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    ElMessage.error("操作失败");
  }
};

// 获取商机详情
const getBusinessDetail = async (businessId) => {
  try {
    // 调用API获取商机详情
    const response = await getBusinessById(businessId);
    if (response.code === 1 && response.data) {
      const business = response.data;
      // 复制商机基本信息到详情和跟进表单
      Object.assign(businessDetail, business);
      Object.assign(followForm.value, business);

      // 处理历史沟通记录，从API返回的trackRecords中提取
      if (business.trackRecords && Array.isArray(business.trackRecords)) {
        trackRecords.value = business.trackRecords.map((record) => ({
          // 格式化时间显示
          followTime: record.createTime
            ? new Date(record.createTime).toLocaleString("zh-CN")
            : "",
          // 处理keyItems字段，接口返回的是字符串格式的数组
          keyItems:
            typeof record.keyItems === "string"
              ? record.keyItems.replace(/[\[\]"']/g, "").split(",")
              : record.keyItems || [],
          trackStatus: record.trackStatus,
          nextTime: record.nextTime,
          record: record.record,
          userName: record.assignName,
        }));
      } else {
        trackRecords.value = [];
      }
    }
  } catch (error) {
    ElMessage.error("获取商机详情失败");
    // 发生错误时清空历史记录
    trackRecords.value = [];
  }
};

// 打开跟进对话框
const openFollowDialog = async (business) => {
  currentBusiness.value = business;

  // 重置表单数据
  Object.assign(followForm, {
    id: business.id,
    phone: business.phone || "",
    name: business.name || "",
    gender: business.gender || null,
    age: business.age || null,
    wechat: business.wechat || "",
    qq: business.qq || null,
    subject: business.subject || null,
    courseId: business.courseId || null,
    degree: business.degree || null,
    jobStatus: business.jobStatus || null,
    channel: business.channel || null,
    remark: business.remark || "",
    trackStatus: null,
    keyItems: [],
    nextTime: business.nextTime || "",
    record: "",
  });

  // 如果有课程信息，更新课程选项
  if (business.subject) {
    const courses = courseStore.getCoursesBySubject(business.subject);
    dynamicCourseOptions.value = courses.map((course) => ({
      label: course.name,
      value: course.id,
    }));
  }

  // 重置表单验证状态
  if (followRef.value) {
    followRef.value.resetFields();
  }

  // 获取商机详情和历史记录
  await getBusinessDetail(business.id);

  // 打开模态框
  dialogVisible.value.followBusiness = true;
};

// 取消跟进
const cancelFollow = () => {
  dialogVisible.value.followBusiness = false;
};

// 格式化跟进状态
const formatTrackStatus = (status) => {
  const statusMap = {
    1: "接通",
    2: "未接通",
    3: "空号",
    4: "拒绝",
  };
  return statusMap[status] || "-";
};

// 确认跟进
const confirmFollow = async () => {
  
  if (!followRef.value || !currentBusiness.value) {
    return;
  }

  try {
    await followRef.value.validate();

    // 转换数据格式
    const followData = {
      ...followForm.value,
      id: currentBusiness.value.id,
      gender: followForm.value.gender ? parseInt(followForm.value.gender) : null,
      age: followForm.value.age ? parseInt(followForm.value.age) : null,
      subject: followForm.value.subject ? parseInt(followForm.value.subject) : null,
      courseId: followForm.value.courseId ? parseInt(followForm.value.courseId) : null,
      degree: followForm.value.degree ? parseInt(followForm.value.degree) : null,
      jobStatus: followForm.value.jobStatus ? parseInt(followForm.value.jobStatus) : null,
      channel: followForm.value.channel ? parseInt(followForm.value.channel) : null,
      trackStatus: followForm.value.trackStatus
        ? parseInt(followForm.value.trackStatus)
        : null,
      // 确保nextTime以正确的ISO格式发送，优化日期格式处理
      nextTime: followForm.value.nextTime && followForm.value.nextTime !== "" ? (() => {
        try {
          // 处理不同格式的时间字符串
          let date;
          if (typeof followForm.value.nextTime === 'string') {
            // 处理 'YYYY-MM-DD HH:mm:ss' 格式
            if (followForm.value.nextTime.includes(' ')) {
              const [datePart, timePart] = followForm.value.nextTime.split(' ');
              const [year, month, day] = datePart.split('-').map(Number);
              const [hours, minutes, seconds] = timePart.split(':').map(Number);
              date = new Date(year, month - 1, day, hours, minutes, seconds || 0);
            } 
            // 处理 'YYYY-MM-DDTHH:mm:ss' 格式
            else if (followForm.value.nextTime.includes('T')) {
              date = new Date(followForm.value.nextTime);
            } else {
              date = new Date(followForm.value.nextTime);
            }
          } else {
            date = new Date(followForm.value.nextTime);
          }
          
          // 检查日期是否有效
          if (!isNaN(date.getTime())) {
            const isoString = date.toISOString();
            return isoString;
          } else {
          }
        } catch (e) {
        }
        return null;
      })() : null
    };

    const response = await followBusiness(followData);
    
    if (response.code === 1) {
      ElMessage.success("跟进记录已保存");
      dialogVisible.value.followBusiness = false;
      await loadBusinesses();
    } else {
      ElMessage.error(response.message || "保存失败");
    }
  } catch (error) {
    if (error.name !== "Error") {
      return; // 表单验证失败
    }
    ElMessage.error("保存失败");
  }
};

// 生命周期钩子
onMounted(async () => {
  await loadBusinesses();
});
</script>

<style scoped>
/* 调整盒模型 */
.business-view {
  padding: 20px;
  box-sizing: border-box;
  background-color: #f0f2f5;
  min-height: 100vh;
}

/* 面包屑导航 */
.bread-crumb {
  margin-bottom: 20px;
}

/* 搜索条件区域 */
.search-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

/* 调整输入框和选择器的宽度 */
:deep(.el-input__wrapper) {
  min-width: 160px;
}

:deep(.el-select) {
  min-width: 160px;
}

/* 操作按钮区域 */
.action-container {
  margin-bottom: 20px;
}

/* 内容整体容器 */
.content-wrapper {
  background-color: #fff;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

/* 表格内容容器 */
.table-wrapper {
  flex: 1;
  overflow: hidden;
  margin-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

/* 分页容器 */
.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 15px 20px;
  background-color: #fff;
  box-sizing: border-box;
  width: 100%;
}

/* 调整表格样式 */
:deep(.el-table) {
  width: 100%;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  font-weight: 500;
  color: #606266;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table td) {
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table__header-wrapper) {
  border-bottom: none;
}

:deep(.el-table__body-wrapper) {
  overflow: visible;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 6px;
  height: 6px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background-color: #dcdfe6;
  border-radius: 3px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  background-color: #f5f7fa;
}

/* 表单行布局 */
.form-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15px;
}

.form-item {
  flex: 1;
  min-width: 250px;
  margin-right: 20px;
  margin-bottom: 0 !important;
}

.form-item:last-child {
  margin-right: 0;
}

/* 确认对话框文本样式 */
.confirm-text {
  text-align: center;
  padding: 20px 0;
  color: #606266;
  font-size: 14px;
  line-height: 20px;
}

/* 状态样式 */
.status-pending {
  color: #e6a23c;
}

.status-waiting {
  color: #409eff;
}

.status-following {
  color: #67c23a;
}

.status-recycled {
  color: #909399;
}

.status-converted {
  color: #f56c6c;
}

.status-default {
  color: #909399;
}

/* 高级搜索样式 */
.advanced-search {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #ebeef5;
}

/* 模态框样式优化 */
:deep(.el-dialog__header) {
  padding: 20px 20px 10px;
}

:deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 10px 20px 20px;
}

/* 操作按钮间距 */
:deep(.el-table .el-button) {
  margin-right: 10px;
}

:deep(.el-table .el-button:last-child) {
  margin-right: 0;
}

/* 加载状态样式 */
:deep(.el-loading-mask) {
  background-color: rgba(255, 255, 255, 0.8);
}

.form-row {
  display: flex;
  margin-bottom: 15px;
}

.form-item {
  flex: 1;
  margin-right: 15px;
}

.form-item:last-child {
  margin-right: 0;
}

.history-section {
  margin-top: 20px;
  border-top: 1px dashed #ebeef5;
  padding-top: 15px;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .business-view {
    padding: 10px;
  }

  .search-container {
    padding: 15px;
  }

  .el-form--inline .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }

  .form-item {
    min-width: 100%;
    margin-right: 0;
  }
}
</style>
